package com.lcf.common.utils;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.lcf.base.constant.SysConstant;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

import static com.lcf.base.constant.SysConstant.DEFAULT_TENANT_ID;
import static com.lcf.base.constant.SysConstant.SESSION_TENANT_ID_KEY;

/**
 * 描述：用户工具类
 *
 * @author lcf
 * @since 2025/2/27 14:41
 */
public class UserUtils {
    private static final ThreadLocal<Long> TENANT_ID_HOLDER = new ThreadLocal<>();

    /**
     * 获取当前登录用户id
     */
    public static long getUserId() {
        return ServletUtils.getRequest() != null && StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : SysConstant.DEFAULT_USER_ID;
    }

    /**
     * 获取租户id
     */
    public static long getTenantId() {
        Long tenantId = TENANT_ID_HOLDER.get();
        if (tenantId == null) {
            String headerTenantId = ServletUtils.getHeader(SESSION_TENANT_ID_KEY);
            tenantId = StringUtils.isBlank(headerTenantId) ? DEFAULT_TENANT_ID : Long.parseLong(headerTenantId);
            setTenantId(tenantId);
        }

        return TENANT_ID_HOLDER.get();
    }

    /**
     * 是否平台管理员
     */
    public static boolean isPlatformAdmin() {
        return Objects.equals(getUserId(), SysConstant.PLATFORM_ADMIN_ID);
    }

    /**
     * 密码明文转密文
     */
    public static String passwordEncrypt(String password) {
        return SaSecureUtil.md5(password + SysConstant.PASSWORD_SALT);
    }

    /**
     * 设置租户id
     */
    public static void setTenantId(long tenantId) {
        TENANT_ID_HOLDER.set(tenantId);
    }

    /**
     * 清除租户id
     */
    public static void clearTenantId() {
        TENANT_ID_HOLDER.remove();
    }
}
